package controllers.systemadmin

import javax.inject.Inject

import controllers.BaseController
import models.{DictItem, DictItemQuery}
import repos.DictItemRepository

import scala.concurrent.ExecutionContext.Implicits.global
class DictItemController @Inject()(dictItemRepository: DictItemRepository) extends BaseController {

  import dictItemRepository.dbConfig.driver.api._
  import models.JsonFormatters._

  def list = authJsonAction[DictItemQuery](Array("admin")) {
    (param, request) =>
      dictItemRepository.filter({ di =>
        param.id.map(di.id === _).getOrElse(LiteralColumn(true)) &&
          param.dictCode.map(di.dictCode === _).getOrElse(LiteralColumn(true)) &&
          param.display.map(di.display like _).getOrElse(LiteralColumn(true)) &&
          param.value.map(di.value === _).getOrElse(LiteralColumn(true))
      }, param.page.getOrElse(1), param.pageSize match {
        case Some(k) => param.pageSize
        case None => Some(25)
      }).map { case (total, items) =>
        Map("success" -> true,
          "resultCode" -> 0,
          "message" -> "list complete",
          "total" -> total,
          "data" -> items)
      }
  }

  def add = authJsonAction[DictItem](Array("admin")) {
    (param, request) =>
      dictItemRepository.save(param)
        .map { di =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "add complete",
            "data" -> di.id)
        }
  }

  def modify = authJsonAction[DictItem](Array("admin")) {
    (param, request) =>
      dictItemRepository.update(param)
        .map(di =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "modify complete")
        )
  }

  def remove = authJsonAction[DictItemQuery](Array("admin")) {
    (param, request) =>
      dictItemRepository.realRemove(param.id.get)
        .map(di =>
          Map("success" -> true,
            "resultCode" -> 0,
            "message" -> "remove complete")
        )
  }

  def single = TODO
}
